import { useEffect, useState, useMemo } from 'react';
import { Button, Card, Form, Space, Spin, message } from 'antd';
import { connect, history } from 'umi';

import pageStyles from '@/common/pageLayout.less';
import ScrollBarLayout from '@/components/ScrollBarLayout';
import { Descriptions, useDescriptions } from '@/components/Descriptions';
import {
  getCompanyID,
  getInvoiceCode,
  getKeyRouter,
  getLoadMapList,
  getPersonalInfo,
  getPosIDs,
  getPosName,
  getTenantID,
  getUserDepID,
  getUserDepName,
  getUserID,
  getUserName,
} from '@/utils';
import { SendOutlined, DiffOutlined, SearchOutlined, RollbackOutlined } from '@ant-design/icons';
import { ILoadMapTypeAll } from '@/common';
import { TagSelectNew as TagSelect } from '@/components/TagSelectNew';

import { SHTG_CHECKSTATE, SHTH_CHECKSTATE, SHZ_CHECKSTATE, closeCurrent, renderFileFunc } from '../../Acommon';

import {
  AddPurchasingMethodChangeServices,
  AddSourceLockServices,
  AddfailureChangeServices,
  EditPurchasingMethodChangeServices,
  GetPurchasingMethodChangeServices,
  alterApplyChangeStateServices,
  editPackProcureRealServices,
  updatePackFlagServices,
  syncPDFtoOAMethodChangeServices,
} from '../services/UpdateService';
import {
  BGbusinessCategory,
  BGflowBusinessType,
  BGorderType,
  BGrequestController,
  FSBG_STATE_CG,
  FSBG_STATE_QC,
  FSBG_STATE_SHZ,
  FSBG_STATE_ZF,
  formatDecimal,
} from '../common/Format';
import { WorkflowChedkRecord, WorkflowSwitchModal, WorkflowNoDefaultTable, WorkflowHndTaskBtn } from '@/components/WorkflowCommonCopy';
import { TipsErrorModalNew } from '@/components/TipsErrorModalNew';
import { UpdateChangeMothedModal } from './UpdateChangeMothedModal';
import { RevokeModal } from '../../Acomponents/RevokeModal';
import { UploadFormCommon } from '@/components/UploadForm';
import moment from 'moment';

/**
 * @UpdateChangeMothed 变更采购方式审批单
 * @returns
 */
const UpdateChangeMothed: React.FC<any> = ({ locationProps, curRes }) => {
  /** info 采购实施-流标按钮跳转过来有值；变更采购方式-正常选择没有值！！！ */
  const { info = {}, sourcePage, type } = locationProps?.state || {}; // 路由携带
  const [changeFromRef] = Form.useForm(); // 表单实例
  const prefixCls = 'apply-update';

  const [isPass, setIsPass] = useState<boolean>(false); // 是否通过线下审批
  const [resObj, setResObj] = useState<Record<string, any>>({ id: null }); // 详情对象保存
  const [iseditReal, setIseditReal] = useState(false); // 是否调用更改标包拟采方式
  const [procureRealList, setProcureRealList] = useState<Record<string, any>[]>(); // 拟定采购方式列表
  const [uploadUrl, setUploadUrl] = useState<string>(''); // 存储上传的文件地址【表单获取不到-未排查到原因】
  const [isShowVerify, setIsShowVerify] = useState(false); // 是否展示确认直接修改拟定采购方式的弹窗
  const [ProjectModal, setProjectModal] = useState<Record<string, any>>({}); //是否显示选择采购项目弹窗
  const [saveSelectInfo, setSaveSelectInfo] = useState<Record<string, any>>({}); // 保存从弹窗中选择的标包信息
  const [procureDraftDisable, setProcureDraftDisable] = useState<string>(''); // 变更前下拉不可选择项
  const [procureRealDisable, setProcureRealDisable] = useState<string>(''); // 拟定下拉不可选择项
  const [invalidState, setInvalidState] = useState<Record<string, any>>({}); // 撤销弹窗

  /** 采购方式字典services */
  const loadMdicIds: string[] = [`${getTenantID()}${ILoadMapTypeAll.PURCHASE_METHOD}`];
  const { loadMapInfo: dictionaryData, mapLoading } = getLoadMapList(loadMdicIds);
  const purchaseFs = dictionaryData?.[`${getTenantID()}${ILoadMapTypeAll.PURCHASE_METHOD}`];

  /** 流程使用state */
  const [isShowWorkRecord, setIsShowWorkRecord] = useState<boolean>(false);
  const [showSwitchFlow, setShowSwitchFlow] = useState<boolean>(false);
  const [workFlowInfoObj, setWorkFlowInfoObj] = useState<Record<string, any>>({
    selectFlowRows: {},
    showWorkFlowModal: false,
    saveNoDefaultFlowID: '',
  });

  const filterList = [
    '100122011011', //实验室-直接采购
    '100122011022', //政府-直接采购
    '100122011021', //定点采购
    '100122011020', //比价-反拍-竞价
  ];
  // 处理树数据
  const orgTreeData = (data: any[], disabledId): any[] => {
    let treeSearch = '';
    const tempData = data.filter((item) => !filterList.includes(item.id));
    return tempData?.map((item: any) => {
      const name = item?.name;
      const nameLength = name?.length;
      const select = name?.search(treeSearch);
      const searchLength = treeSearch?.length;
      const afterStr = name?.slice(0, select);
      const selectStr = treeSearch;
      const beforeStr = name?.slice(select + searchLength, nameLength);
      const titleTree =
        select > -1 && selectStr ? (
          <span className={pageStyles['over-flow-hidden']}>
            {afterStr}
            <span style={{ color: '#f50' }}>{selectStr}</span>
            {beforeStr}
          </span>
        ) : (
          <span className={pageStyles['over-flow-hidden']}>{item?.name}</span>
        );

      return {
        ...item,
        title: <div id={item?.id}>{titleTree}</div>,
        searchTitle: item?.name,
        key: item?.id,
        value: item?.id,
        // disabled: item?.id === changeFromRef.getFieldValue('procureDraft'), //互斥代码，需求变动时可以参考
        disabled: item?.id === disabledId,
      };
    });
  };

  /** 是否可以编辑 */
  const isEditState = useMemo(() => {
    if (sourcePage == 'source') return true;
    if (type == 'view') return false;

    if (!resObj?.id && curRes?.['/purchaseSourceChangeController/add']) {
      return true;
    } else if (
      resObj?.id &&
      resObj?.state == FSBG_STATE_QC() &&
      !resObj?.checkState &&
      curRes?.['/purchaseSourceChangeController/edit'] &&
      resObj?.createPositionID == getPosIDs() &&
      resObj?.createrID == getUserID()
    ) {
      return true;
    } else if (
      resObj?.id &&
      resObj?.state == FSBG_STATE_SHZ() &&
      resObj?.checkState == SHTH_CHECKSTATE() &&
      resObj?.applyPositionID == getPosIDs() &&
      resObj?.applyerID == getUserID() &&
      curRes?.['/purchaseSourceChangeController/edit']
    ) {
      return true;
    } else {
      return false;
    }
  }, [curRes, resObj, sourcePage, type]);

  // 表格表单配置信息
  const [config, { setFieldsValue }] = useDescriptions({
    labelWidth: 200,
    basicForm: changeFromRef,
    schemas: [
      {
        label: '变更采购方式申请',
        field: 'Title',
        component: 'Title',
      },
      {
        label: '申请日期',
        field: 'applyTime',
        component: 'Input',
        placeholder: '自动带出',
        initialValue: moment(new Date()).format('YYYY-MM-DD'),
        disabled: true,
        required: false,
      },
      {
        label: '流水单号',
        field: 'changeCode',
        component: 'Input',
        placeholder: '自动带出',
        initialValue: getInvoiceCode('BG'),
        disabled: true,
      },
      {
        label: '申请人',
        field: 'createrName',
        component: 'Input',
        placeholder: '自动带出',
        disabled: true,
      },
      {
        label: '联系电话',
        field: 'applyPhone',
        component: 'Input',
        // disabled: !isEditState,
        placeholder: '自动带出',
        disabled: true,
      },
      {
        label: '申请部门/单位',
        field: 'createDepartmentName',
        component: 'Input',
        placeholder: '自动带出',
        disabled: true,
      },
      {
        label: '职务岗位',
        field: 'applyPositionName',
        component: 'Input',
        placeholder: '自动带出',
        disabled: true,
      },
      {
        label: '采购项目名称',
        field: 'applyTitle',
        component: 'Input',
        placeholder: '请选择',
        required: true,
        disabled: true,
        contentAfter:
          type != 'view' && !resObj?.id ? (
            sourcePage == 'source' ? null : (
              <a>
                <SearchOutlined onClick={() => setProjectModal({ isShow: true })} />
              </a>
            )
          ) : null,
      },
      {
        label: '标包名称',
        field: 'packName',
        component: 'Input',
        placeholder: '自动带出',
        disabled: true,
      },
      {
        label: '变更前采购方式',
        field: 'procureDraft',
        component: 'TreeSelect',
        placeholder: '请选择',
        required: false,
        treeData: orgTreeData(procureRealList || [], procureDraftDisable),
        disabled: true,
        onSelect: (val) => setProcureRealDisable(val),
      },
      {
        label: '拟采用采购方式',
        placeholder: '请选择',
        field: 'procureReal',
        component: 'TreeSelect',
        required: true,
        treeData: orgTreeData(procureRealList || [], procureRealDisable),
        disabled: !isEditState,
        onSelect: (val) => setProcureDraftDisable(val),
      },
      {
        label: '预算金额',
        field: 'expectSum',
        placeholder: '自动带出',
        component: 'Input',
        disabled: true,
        contentAfter: '元',
      },
      {
        label: '审批方式',
        field: 'applyFlag',
        component: 'Render',
        colSpan: 1,
        required: true,
        disabled: !isEditState && !resObj?.checkState,

        slotRender: (text) => {
          if (isEditState) {
            return (
              <div style={{ marginLeft: 8 }}>
                <TagSelect
                  colSpan={24}
                  formLabel={''}
                  formName={'applyFlag'}
                  defalultKeys={Number(text)}
                  onChange={(val) => setIsPass(Boolean(val))}
                  radioDisabled={resObj?.state == FSBG_STATE_SHZ()}
                  radioList={[
                    {
                      value: 0,
                      name: '线上',
                    },
                    {
                      value: 1,
                      name: '线下',
                    },
                  ]}
                />
              </div>
            );
          } else {
            let textName = text == '1' ? '线下' : '线上';
            return <span style={{ marginLeft: 8 }}>{textName}</span>;
          }
        },
      },
      {
        label: '相关附件',
        field: 'applyURL',
        placeholder: '请上传相关附件',
        component: 'Render',
        colSpan: 2,
        required: isPass ? true : false,
        slotRender: (text, record) => {
          if (isEditState) {
            return (
              <div>
                <UploadFormCommon
                  form={changeFromRef}
                  fileFormName={'applyURL'}
                  spanCol={24}
                  inRowProportion={24}
                  name={'attachFile'}
                  required={isPass ? true : false}
                  accept={'.doc|.docx'}
                  url={'/purchaseSourceChangeController/uploadFile'}
                  downloadUrl={'/purchaseSourceChangeController/downloadFile'}
                  fileFormDelName={'delFile'}
                  uploadSuccessCallback={(attachPaths) => {
                    setUploadUrl(attachPaths);
                  }}
                  defaultFiles={text}
                  maxFile={1}
                  hintTitle={'且只能上传 1 个！'}
                  fieldBusiPath={'purchase/change'}
                  delFunc={(delFilePath) => {
                    setUploadUrl('');
                  }}
                >
                  上传
                </UploadFormCommon>
              </div>
            );
          } else {
            return (
              <div style={{ marginLeft: 8 }}>
                {renderFileFunc({ record: resObj, fileName: 'applyURL', downloadAddress: '/purchaseSourceChangeController/downloadFile' })}
              </div>
            );
          }
        },
      },
      {
        label: '采购方式变更理由',
        field: 'applyInfo',
        placeholder: '请输入',
        component: 'InputTextArea',
        required: true,
        showCount: true,
        allowClear: true,
        maxLength: 800,
        autoSize: { minRows: 6, maxRows: 8 },
        colSpan: 2,
        disabled: !isEditState,
      },
    ],
  });

  /** <<<================================实施流标 - 锁定状态================================>>> */
  const { AddSourceLockRun, AddSourceLockLoading } = AddSourceLockServices((res) => {
    if (res?.msgFlag) {
      message?.success(res?.msg);
    }
  });

  /** <<<================================实施流标 - 添加实施================================>>> */
  const { AddfailureChangeRun, AddfailureChangeLoading } = AddfailureChangeServices((res) => {
    if (res?.msgFlag) {
      message?.success(res?.msg);
      alterApplyChangeStateChangeRun({
        applyCompanyID: resObj?.applyCompanyID,
        applyDepartmentID: resObj?.applyDepartmentID,
        applyPositionID: resObj?.applyPositionID,
        applyerID: resObj?.applyerID,
        state: FSBG_STATE_CG(),
        id: resObj?.id,
        versionNum: resObj?.versionNum,
      });
    }
  });

  /** <<<================================获取采购申请变更工单Services================================>>> */
  const { GetPurchasingMethodChangeRun, GetPurchasingMethodChangeLoading } = GetPurchasingMethodChangeServices((res) => {
    if (res?.msgFlag) {
      let returnObj = res?.obj;

      message?.success(res?.msg);
      setResObj(returnObj);
      setUploadUrl(returnObj?.applyURL);

      setSaveSelectInfo({
        projectFlag: returnObj?.projectFlag,
        projectID: returnObj?.projectID,
        packID: returnObj?.packID,
        sourceID: returnObj?.sourceID,
        procureOrg: returnObj?.procureOrg,
        expectSum: returnObj?.expectSum,
        applyID: returnObj?.applyID,
        purchProjectCode: returnObj?.purchProjectCode,
        purchProjectName: returnObj?.purchProjectName,
        applyTime: moment(returnObj?.applyTime).format('YYYY-MM-DD'),
        changeCode: returnObj?.changeCode,
        applyPositionName: returnObj?.applyPositionName,
      });

      setProcureDraftDisable(returnObj?.procureReal);
      setProcureRealDisable(returnObj?.procureDraft);

      setFieldsValue({
        ...returnObj,
        applyTitle: returnObj?.purchProjectName,
        packName: returnObj?.packName,
        expectSum: formatDecimal(returnObj?.expectSum),
        applyTime: moment(returnObj?.applyTime).format('YYYY-MM-DD'),
        changeCode: returnObj?.changeCode,
        applyPositionName: returnObj?.applyPositionName,
      });

      if (returnObj?.applyFlag == 1) {
        setIsPass(true);
      }
      if (returnObj?.state == FSBG_STATE_SHZ() && returnObj?.checkState == SHZ_CHECKSTATE()) {
        setIseditReal(true);
      }

      /** 如果是实施来的 - 触发锁定功能 && curRes?.['/purchaseSourceController/addLock'] */
      if (sourcePage === 'source') {
        AddSourceLockRun({ id: info?.sourceID });
      }
    }
  });

  /** <<<================================添加采购申请变更工单Services================================>>> */
  const { AddPurchasingMethodChangeRun, AddPurchasingMethodChangeLoading } = AddPurchasingMethodChangeServices((res) => {
    if (res?.msgFlag) {
      message?.success(res?.msg);
      let { obj } = res;
      GetPurchasingMethodChangeRun({ id: obj });
    }
  });

  /** <<<================================编辑采购申请变更工单Services================================>>> */
  const { EditPurchasingMethodChangeRun, EditPurchasingMethodChangeLoading } = EditPurchasingMethodChangeServices((res) => {
    if (res?.msgFlag) {
      message?.success(res?.msg);
      let { obj } = res;
      GetPurchasingMethodChangeRun({ id: obj });
    }
  });

  /** <<<================================改变【变更采购申请】工单状态的services================================>>> */
  const { alterApplyChangeStateChangeRun, alterApplyChangeStateLoading } = alterApplyChangeStateServices((res) => {
    if (res?.msgFlag) {
      message?.success(res?.msg);
      GetPurchasingMethodChangeRun({ id: resObj?.id });
    }
  });

  /** <<<================================改变标包拟采方式Services================================>>> */
  const { editPackProcureRealChangeRun, editPackProcureRealChangeLoading } = editPackProcureRealServices((res) => {
    if (res?.msgFlag) {
      alterApplyChangeStateChangeRun({
        applyCompanyID: resObj?.applyCompanyID,
        applyDepartmentID: resObj?.applyDepartmentID,
        applyPositionID: resObj?.applyPositionID,
        applyerID: resObj?.applyerID,
        state: FSBG_STATE_CG(),
        id: resObj?.id,
        versionNum: resObj?.versionNum,
      });
    }
  });

  /***/
  const { syncPDFtoOARun, syncPDFtoOALoading } = syncPDFtoOAMethodChangeServices((res) => {});

  const syncPDFtoOARunfun = (infoObj) => {
    let resObj = { ...infoObj, paramObject: null };
    syncPDFtoOARun(resObj);
  };

  /** @submit 提交事件 */
  const submit = async (flag) => {
    if (type == 'view') {
      setWorkFlowInfoObj({
        selectFlowRows: { ...resObj },
        showWorkFlowModal: true,
        saveNoDefaultFlowID: '',
      });
      return;
    }

    /** 获取表单内容 */
    const result = await changeFromRef?.validateFields();
    let params = {
      ...result,
      businessType: BGflowBusinessType(),
      state: FSBG_STATE_QC(),
    };
    if (!resObj?.id) {
      let addParams = {
        ...params,
        applyURL: uploadUrl,
        sourceID: saveSelectInfo?.sourceID,
        packID: saveSelectInfo?.packID,
        projectFlag: saveSelectInfo?.projectFlag,
        projectID: saveSelectInfo?.projectID,
        applyID: saveSelectInfo?.applyID,
        purchProjectCode: saveSelectInfo?.purchProjectCode,
        purchProjectName: saveSelectInfo?.purchProjectName,
        applyTime: moment(new Date()).format('YYYY-MM-DD HH:mm:ss'),
        applyCompanyID: getCompanyID(),
        applyDepartmentID: getUserDepID(),
        applyPositionID: getPosIDs(),
        applyerID: getUserID(),
        createrID: getUserID(),
        createPositionID: getPosIDs(),
        createDepartmentID: getUserDepID(),
        createCompanyID: getCompanyID(),
      };

      if (sourcePage === 'source') {
        //实施流标变更-数据标识
        addParams.difFlag = 1;
      }

      /**新增接口*/
      await AddPurchasingMethodChangeRun(addParams)?.then((res) => {
        if (res?.msgFlag && flag) {
          if (addParams?.applyFlag) {
            setIsShowVerify(true);
          } else {
            setWorkFlowInfoObj({
              selectFlowRows: { ...addParams, id: res?.obj },
              showWorkFlowModal: true,
              saveNoDefaultFlowID: '',
            });
          }
        }
      });
    } else {
      let editParams = {
        ...resObj,
        ...params,
        // applyInfo: result?.applyInfo,
        // sourceID: saveSelectInfo?.sourceID,
        // packID: saveSelectInfo?.packID,
        // projectFlag: saveSelectInfo?.projectFlag,
        // projectID: saveSelectInfo?.projectID,
        // applyID: saveSelectInfo?.applyID,
        // purchProjectCode: saveSelectInfo?.purchProjectCode,
        // purchProjectName: saveSelectInfo?.purchProjectName,
      };
      /**编辑接口*/
      await EditPurchasingMethodChangeRun(editParams)?.then((res) => {
        if (res?.msgFlag && flag) {
          if (editParams?.applyFlag) {
            setIsShowVerify(true);
          } else {
            setWorkFlowInfoObj({
              selectFlowRows: editParams,
              showWorkFlowModal: true,
              saveNoDefaultFlowID: '',
            });
          }
        }
      });
    }
  };

  /** 在审核通过后自动触发更改拟采方式接口 */
  useEffect(() => {
    if (resObj?.checkState == SHTG_CHECKSTATE() && resObj?.state == FSBG_STATE_CG()) {
      if (iseditReal) {
        if (resObj?.difFlag == 1) {
          setIseditReal(false);
          AddfailureChangeRun({
            id: resObj?.sourceID,
            procureDraft: resObj?.procureDraft,
            procureReal: resObj?.procureReal,
            ownPhone: getPersonalInfo()?.phoneMobile,
            sourceCode: getInvoiceCode('SS'),
          });
        } else {
          setIseditReal(false);
          editPackProcureRealChangeRun({
            procureOrg: saveSelectInfo?.procureOrg,
            id: resObj?.packID,
            procureReal: resObj?.procureReal,
          });
        }
      }
    }
  }, [iseditReal, resObj]);

  /** 修改采购分包是否变更状态接口 */
  const { updatePackFlagRun, updatePackFlagLoading } = updatePackFlagServices((res) => {
    if (res?.msgFlag) {
      message.success(res?.msg);
    } else {
      message.error(res?.msg);
    }
  });

  /** 审核中，审核通过/作废 开关 */
  const [isSHTGFlag, setIsSHTGFlag] = useState(false);

  /** 监听数据状态改变，更改状态 */
  useEffect(() => {
    if (
      (resObj?.state && resObj?.state == `${getTenantID()}${ILoadMapTypeAll.PURCHASE_CHANGEWAY}1001` && resObj?.checkState == SHZ_CHECKSTATE()) ||
      (resObj?.state == `${getTenantID()}${ILoadMapTypeAll.PURCHASE_CHANGEWAY}1001` && resObj?.checkState == SHTH_CHECKSTATE())
    ) {
      setIsSHTGFlag(true);
    }
    if (
      isSHTGFlag &&
      (resObj?.state == `${getTenantID()}${ILoadMapTypeAll.PURCHASE_CHANGEWAY}1002` ||
        resObj?.state == `${getTenantID()}${ILoadMapTypeAll.PURCHASE_CHANGEWAY}1003`)
    ) {
      // 修改采购分包是否变更状态接口
      updatePackFlagRun({
        changeID: resObj?.id,
        changeFlag: 0,
      });
    }
  }, [resObj?.state, resObj?.checkState]);

  /** 回显数据 【TODO: 后续拿包id查包详情】*/
  useEffect(() => {
    let { changeID } = info;
    if (changeID) {
      GetPurchasingMethodChangeRun({ id: changeID });
    } else {
      if (sourcePage == 'source') {
        setSaveSelectInfo({
          projectFlag: info?.projectFlag,
          projectID: info?.projectID,
          packID: info?.packID,
          sourceID: info?.sourceID,
          procureOrg: info?.procureOrg,
          applyID: info?.applyID,
          purchProjectCode: info?.purchProjectCode,
          purchProjectName: info?.purchProjectName,
          applyTime: moment(info?.applyTime).format('YYYY-MM-DD'),
          applyPositionName: info?.applyPositionName,
          changeCode: info?.changeCode,
        });
      }
      setFieldsValue({
        ...info,
        applyTime: moment(info?.applyTime).format('YYYY-MM-DD'),
        createrName: getUserName(),
        createDepartmentName: getUserDepName(),
        applyPositionName: getPosName(),
        applyPhone: getPersonalInfo()?.phoneMobile || '',
        changeCode: getInvoiceCode('BG'),
        applyFlag: 0,
      });
    }
  }, [info]);

  /** 根据采购组织类型，渲染采购方式列表 */
  useEffect(() => {
    if (saveSelectInfo?.procureOrg && purchaseFs) {
      const purchaseFsObj = purchaseFs?.find((item) => item?.id === saveSelectInfo?.procureOrg);
      setProcureRealList(purchaseFsObj?.children || []);
    }
  }, [saveSelectInfo?.procureOrg, purchaseFs]);

  /** 原本在工单详情接口根据返回的采购方式找对应的采购组织形式下的列表，但是放到详情会有异步问题，就是工单详情请求到了，但是采购方式字典没请求完，所以放这里监听 */
  useEffect(() => {
    if (!saveSelectInfo?.procureOrg && resObj?.procureReal) {
      const result = purchaseFs?.find((item) => {
        return item?.children?.find((ite) => {
          return ite?.id === resObj?.procureReal;
        });
      });
      setSaveSelectInfo({
        ...saveSelectInfo,
        procureOrg: result?.id,
      });
    }
  }, [saveSelectInfo, resObj]);

  /** all-Loading */
  const allLaoding = useMemo(() => {
    return (
      EditPurchasingMethodChangeLoading ||
      AddPurchasingMethodChangeLoading ||
      GetPurchasingMethodChangeLoading ||
      editPackProcureRealChangeLoading ||
      alterApplyChangeStateLoading ||
      mapLoading ||
      AddSourceLockLoading ||
      AddfailureChangeLoading ||
      updatePackFlagLoading
    );
  }, [
    EditPurchasingMethodChangeLoading,
    AddPurchasingMethodChangeLoading,
    GetPurchasingMethodChangeLoading,
    editPackProcureRealChangeLoading,
    alterApplyChangeStateLoading,
    mapLoading,
    AddSourceLockLoading,
    AddfailureChangeLoading,
    updatePackFlagLoading,
  ]);

  /** 处理工作流功能 权限 */
  const workflowPowerAllBtn = useMemo(() => {
    let pownerBtn: Record<string, any> = {
      revokeFlagBtn: false, //撤销按钮
      invalBoolBtn: false, //暂停开始按钮
      stopProcInstBtn: false, //流程作废接口
    };
    if (resObj?.state == FSBG_STATE_SHZ()) {
      pownerBtn['revokeFlagBtn'] = true;
      pownerBtn['stopProcInstBtn'] = true;
    }

    const taskType: string = BGflowBusinessType();
    const taskHandInfo: Record<string, any> = resObj?.paramObject?.[taskType];
    if (
      taskHandInfo &&
      taskHandInfo?.mactivitiTaskList?.length > 0 &&
      taskHandInfo?.mactivitiTaskList?.[0]?.assigneePositionID == getPosIDs() &&
      taskHandInfo?.mactivitiTaskList?.[0]?.assigneeID == getUserID()
    ) {
      pownerBtn['invalBoolBtn'] = true;
    }
    return pownerBtn;
  }, [resObj]);

  /** 关闭切换流程modal方法 */
  const closeSwitchFlowModal = (isDefaultModal: boolean) => {
    if (isDefaultModal) {
      setWorkFlowInfoObj({
        ...workFlowInfoObj,
        showWorkFlowModal: true,
      });
    } else {
      setShowSwitchFlow(false);
    }
  };

  return (
    <div className={prefixCls + '-UpdataIntentBox'}>
      <Spin spinning={allLaoding}>
        <Card
          title={'变更采购方式申请'}
          className={pageStyles['page-view-cardView']}
          bodyStyle={{ padding: 0 }}
          extra={
            <Space>
              {isEditState && resObj?.state !== FSBG_STATE_CG() && (
                <Button
                  // icon={<DiffOutlined />}
                  type="primary"
                  onClick={() => submit(false)}
                >
                  暂存
                </Button>
              )}
              {(resObj?.state == FSBG_STATE_QC() || !resObj?.state) &&
                !resObj?.checkState &&
                curRes?.['/purchaseSourceChangeController/startProcess/{starterDeptID}'] && (
                  <Button
                    // icon={<SendOutlined />}
                    type="primary"
                    onClick={() => submit(true)}
                  >
                    提交
                  </Button>
                )}
              {locationProps?.state?.returnPathName && (
                <Button danger onClick={() => closeCurrent(locationProps?.state?.returnPathName)}>
                  关闭
                </Button>
              )}

              <WorkflowHndTaskBtn
                flowDetailInfo={resObj}
                flowBusinessType={BGflowBusinessType()}
                requestController={BGrequestController()}
                reloadCallback={() => GetPurchasingMethodChangeRun({ id: resObj?.id })}
                applyHeader={'apply'}
                revokeRequestUrl={'/purchaseSourceChangeController/invalid'}
                revokeRequestState={`${getTenantID()}${ILoadMapTypeAll?.PURCHASE_CHANGEWAY}`}
                isShowRevokeStateList={[FSBG_STATE_SHZ()]}
                revokeTitle={resObj?.packName}
                revokeSuccessCallback={() => {
                  history.push({
                    pathname: `/purchaseSourceChangeController/edit/:${getKeyRouter()}${getKeyRouter()}`,
                    state: {
                      info: { changeID: resObj?.id },
                      type: 'edit',
                      delRouterName: history?.location?.pathname,
                      returnPathName: locationProps?.state?.returnPathName,
                    },
                  });
                }}
              />
            </Space>
          }
        >
          <div className={`${prefixCls}-container`}>
            <ScrollBarLayout style={{ padding: 5 }}>
              <Descriptions config={config} />
            </ScrollBarLayout>
          </div>
          {
            <div className={`${prefixCls}-footer`}>
              <Space>
                {(resObj?.state == FSBG_STATE_QC() || !resObj?.state) &&
                  !resObj?.checkState &&
                  curRes?.['/purchaseSourceChangeController/startProcess/{starterDeptID}'] && (
                    <Button
                      // icon={<SendOutlined />}
                      type="primary"
                      onClick={() => submit(true)}
                    >
                      提交
                    </Button>
                  )}

                {locationProps?.state?.returnPathName && (
                  <Button danger onClick={() => closeCurrent(locationProps?.state?.returnPathName)}>
                    关闭
                  </Button>
                )}
              </Space>
            </div>
          }
        </Card>

        {/* 工作流-----审批记录 */}
        {resObj?.paramObject?.[BGflowBusinessType()] && (
          <WorkflowChedkRecord
            curRes={curRes}
            dataDetailInfo={resObj}
            flowBusinessType={BGflowBusinessType()}
            requestController={BGrequestController()}
            reloadPageCallback={() => {
              GetPurchasingMethodChangeRun({ id: resObj?.id });
            }} // 刷新方法-详情方法
            revokeStateID={FSBG_STATE_QC()}
            allBtnFuncQuqry={workflowPowerAllBtn}
            tabPaneHeight={0.35}
            isCheckDrawer={true}
            isShowCollapse={isShowWorkRecord}
            changeCollapse={(val) => {
              setIsShowWorkRecord(val);
            }}
            cancelStateId={FSBG_STATE_ZF()}
            isSyncArchive={true}
          />
        )}

        {/* 工作流-----发起流程审批弹窗 */}
        {workFlowInfoObj?.showWorkFlowModal && (
          <WorkflowSwitchModal
            openVisible={workFlowInfoObj?.showWorkFlowModal}
            businessInfoObj={workFlowInfoObj?.selectFlowRows}
            requestController={BGrequestController()}
            orderType={workFlowInfoObj?.selectFlowRows?.orderType || BGorderType()}
            category={BGflowBusinessType()}
            businessCategory={BGbusinessCategory()}
            selectFlowID={workFlowInfoObj?.saveNoDefaultFlowID}
            reloadInfoCallback={() => {
              // GetPurchasingMethodChangeRun({ id: resObj?.id });
              history.push({
                pathname: `/purchaseSourceChangeController/getSourceChangeById/{id}/{currentUserID}/:${getKeyRouter()}${getKeyRouter()}`,
                state: {
                  info: { changeID: resObj?.id, applyTitle: resObj?.purchProjectName, packName: resObj?.packName },
                  type: 'view',
                  delRouterName: history?.location?.pathname,
                  returnPathName: locationProps?.state?.returnPathName,
                },
              });
            }}
            openFlowChangeModal={setShowSwitchFlow}
            onClose={() => {
              setWorkFlowInfoObj({
                ...workFlowInfoObj,
                showWorkFlowModal: false,
              });
            }}
            replaceStrObj={{
              own: 'apply',
              workflowType: 'category',
            }}
          />
        )}

        {/* 工作流-----挑选流程组件 */}
        {showSwitchFlow && (
          <WorkflowNoDefaultTable
            openVisibleSwitch={showSwitchFlow}
            onCloseSwitch={closeSwitchFlowModal}
            requestController={BGrequestController()}
            orderType={workFlowInfoObj?.selectFlowRows?.orderType || BGorderType()}
            category={BGflowBusinessType()}
            businessCategory={BGbusinessCategory()}
            saveSelectFlowID={(flowId: string) => {
              setWorkFlowInfoObj({
                ...workFlowInfoObj,
                saveNoDefaultFlowID: flowId,
              });
            }}
            selectFlowID={workFlowInfoObj?.saveNoDefaultFlowID}
          />
        )}

        {isShowVerify && (
          // 提交提示框
          <TipsErrorModalNew
            onClose={() => setIsShowVerify(false)}
            modalOnOK={() => {
              if (resObj?.difFlag == 1) {
                AddfailureChangeRun({
                  id: resObj?.sourceID,
                  procureDraft: resObj?.procureDraft,
                  procureReal: resObj?.procureReal,
                  ownPhone: getPersonalInfo()?.phoneMobile,
                  sourceCode: getInvoiceCode('SS'),
                });
              } else {
                editPackProcureRealChangeRun({
                  procureOrg: saveSelectInfo?.procureOrg,
                  id: resObj?.packID,
                  procureReal: resObj?.procureReal,
                  // versionNum: info?.packVersionNum,
                });
                // 修改采购分包是否变更状态接口
                updatePackFlagRun({
                  changeID: resObj?.id,
                  changeFlag: 0,
                });
              }

              syncPDFtoOARunfun(resObj); /**推送至档案接口*/
            }}
            modalTip={resObj?.difFlag === 1 ? '请确认变更申请信息无误，提交后将生成新的文件编制！' : '本操作会变更采购方式，请确认信息是否有误！'}
            modalLoading={editPackProcureRealChangeLoading}
            bodyWidth={0.25}
          />
        )}

        {ProjectModal?.isShow && (
          <UpdateChangeMothedModal
            onSave={(value) => {
              let { applyInfo, packInfo } = value;
              setSaveSelectInfo({
                projectFlag: applyInfo?.projectFlag,
                projectID: applyInfo?.projectID,
                applyID: applyInfo?.id,
                purchProjectCode: applyInfo?.purchProjectCode,
                purchProjectName: applyInfo?.purchProjectName,
                procureDraft: packInfo?.procureReal,
                packID: packInfo?.id,
                sourceID: packInfo?.sourceID,
                procureOrg: packInfo?.procureOrg,
                expectSum: packInfo?.expectSum,
              });
              setFieldsValue({
                procureDraft: packInfo?.procureReal,
                applyTitle: applyInfo?.applyTitle,
                packName: packInfo?.packName,
                expectSum: formatDecimal(packInfo?.expectSum),
              });
            }}
            onClose={() => {
              setProjectModal({});
            }}
            curRes={curRes}
          />
        )}
      </Spin>
    </div>
  );
};

export default connect(({ navTab, baseLogin }: Record<string, any>) => ({
  navTab,
  curRes: baseLogin?.permissions,
}))(UpdateChangeMothed);
